package com.yxjx.duoxue.my;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.Executors;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.course.CourseIntroductionActivity;
import com.yxjx.duoxue.course.CourseListActivity;
import com.yxjx.duoxue.customview.autolist.AutoListView;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnLoadListener;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnRefreshListener;
import com.yxjx.duoxue.datamodel.DMActivity;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class FavouriteCoursesActivity extends BaseActionBarActivity implements
		OnRefreshListener, OnLoadListener {
	public static final int MSG_CODE_VIEW_COURSE = 1;
	
	public static final int PAGE_ACTIVITY_NUM = 20;
	
	private FavouriteCoursesAdapter mAdapter;
	private AutoListView mList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_favourite_courses);
		
		mList = (AutoListView) findViewById(R.id.list);
		mAdapter = new FavouriteCoursesAdapter();
		mList.setAdapter(mAdapter);
		mList.setOnRefreshListener(this);
		mList.setOnLoadListener(this);
		mList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				if (arg2 >= mAdapter.getCount() + 1 || arg2 == 0) {
					return;
				}
				
				DMCourse course = mAdapter.getData().get(arg2 - 1);
				Intent intent = new Intent(getApplicationContext(), CourseIntroductionActivity.class);
				intent.putExtra(NwUtils.KEY_ID, "" + course.getCourseId());
				startActivityForResult(intent, MSG_CODE_VIEW_COURSE);
				
			}
		});

		customizeActionBarTitle("收藏课程");
		requestAllFavouriteCourses();
	}

	private void requestAllFavouriteCourses() {
		JSONObject param = new JSONObject();
		try {
			param.put("startIndex", "0");
			param.put("count","20");
			param.put("time", "" + System.currentTimeMillis());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		requestCoursesByParams(param, AutoListView.REFRESH);
	}
	
	private void requestsMoreFavouriteCourses() {
		JSONObject param = new JSONObject();
		int startIndex = mAdapter.getCount();
		try {
			param.put("startIndex", "" + startIndex);
			param.put("count","20");
			param.put("time", "" + System.currentTimeMillis());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		requestCoursesByParams(param, AutoListView.LOAD);
	}
	
	private void requestCoursesByParams(JSONObject params, int callbackId) {
		FavouriteListAsyncTask task = new FavouriteListAsyncTask();
		task.execute(params.toString(), "" + callbackId);
	}
	
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			switch(arg0.getId()) {
			case R.id.to_find:
				//
				UIHelper.LoadingActivity(FavouriteCoursesActivity.this,
						new Intent(getApplicationContext(),
								CourseListActivity.class));
				FavouriteCoursesActivity.this.finish();
				break;
			default:
				mBaseClickListener.onClick(arg0);
				break;
			}
		}
	};
	
	public void toFind(View view) {
		UIHelper.LoadingActivity(FavouriteCoursesActivity.this,
				new Intent(getApplicationContext(),
						CourseListActivity.class));
		FavouriteCoursesActivity.this.finish();
	}
	
	private Handler mHandler = new Handler() {
    	@Override
    	public void handleMessage(android.os.Message msg) {
    		ArrayList<DMCourse> result = (ArrayList<DMCourse>) msg.obj;
    		switch (msg.what) {
			case AutoListView.REFRESH:
				removeMessages(AutoListView.REFRESH);
				mAdapter.setData(result);
				new FinishRefresh().execute();
				// try to progress dialog
				dismissProgressDialog();
				resetScroll();
				break;
			case AutoListView.LOAD:
				removeMessages(AutoListView.LOAD);
				mAdapter.addData(result);
				new FinishRefresh().execute();
				break;
			default:
				break;
			}
    		mList.setResultSize(result == null ? 0 : result.size());
    	}
    };
    
	private void dismissProgressDialog() {
			
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
		if (mAdapter != null && mAdapter.getCount() > 0) {
			findViewById(R.id.list).setVisibility(View.VISIBLE);
			findViewById(R.id.empty).setVisibility(View.INVISIBLE);
		} else {
			findViewById(R.id.empty).setVisibility(View.VISIBLE);
			findViewById(R.id.list).setVisibility(View.INVISIBLE);
		}
	}
    
	class FavouriteCoursesAdapter extends BaseAdapter {
		
		private ArrayList<DMCourse> mDatas = new ArrayList<DMCourse>();
		
		public ArrayList<DMCourse> getData() {
			return mDatas;
		}
		
		public void addData(ArrayList<DMCourse> result) {
			mDatas.addAll(result);
			notifyDataSetChanged();
		}

		public void setData(ArrayList<DMCourse> data) {
			mDatas = data;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			if (mDatas == null) {
				return 0;
			}
			return mDatas.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_course_list_1, null);
			} else {
				ret = arg1;
			}
			final DMCourse course = mDatas.get(arg0);
			UIHelper.setText(ret, R.id.course_name, course.getCourseName());
			((TextView) ret.findViewById(R.id.category)).setText(Utils.getCategoryText(course));
			UIHelper.setText(ret, R.id.school_name, course.getSchoolFullName());
			UIHelper.asyncLoadImage((ImageView) ret.findViewById(R.id.icon), course.getHeadImageUrl(), R.drawable.default_icon);
			((TextView) ret.findViewById(R.id.location_info)).setText(Utils.getDistanceDesc(getApplicationContext(), course.getSchoolGps()));

			return ret;
		}
	}
	
	class FavouriteListAsyncTask extends AsyncTask<String, Integer, ArrayList<DMCourse>> {
		
		private int mCallbackId;

		@Override
		protected ArrayList<DMCourse> doInBackground(String... arg0) {
			UserLoginResponse ulRsp = UserLoginResponse.getInstance(getApplicationContext());
			String paramStr = arg0[0];
			mCallbackId = Integer.valueOf(arg0[1]);
			JSONObject param = null;
			try {
				param = new JSONObject(paramStr);
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			
			try {
				return UserReg.requestFavouriteCourses(ulRsp, Yx.TYPE_ITEM_COURSE, param, FavouriteCoursesActivity.this);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(ArrayList<DMCourse> result) {
			super.onPostExecute(result);
			mHandler.sendMessage(mHandler.obtainMessage(mCallbackId, result));
		}
	}

	@Override
	public void onLoad() {
		requestsMoreFavouriteCourses();
	}

	@Override
	public void onRefresh() {
		requestAllFavouriteCourses();
	}
	
	private void resetScroll() {
		mList.post(new Runnable() {
			
			@Override
			public void run() {
				mList.setSelection(0);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		switch (arg0) {
		case MSG_CODE_VIEW_COURSE:
			if (arg1 == RESULT_OK) {
				DMCourse course = (DMCourse) arg2.getExtras().getSerializable(Yx.KEY_COURSE_OBJECT);
				updateFavourites(mAdapter.getData(), course);
			}
			break;
		default:
			break;
		}
	}
	
	private void updateFavourites(ArrayList<DMCourse> list, DMCourse item) {
		Iterator<DMCourse> iterator = list.iterator();
		while (iterator.hasNext()) {
			DMCourse listItem = iterator.next();
			if (listItem.getCourseId() == item.getCourseId() && item.getFavStatus() == 0) {
				iterator.remove();
				break;
			}
		}
		mAdapter.notifyDataSetChanged();
		dismissProgressDialog();
	}
	
	private class FinishRefresh extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... arg0) {
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			mList.onRefreshComplete();
		}
		
	}
	
}
